// JavaScript Document

var quick_links = {

	// stores a reference to the currently loaded article category for quick addition
    category_id: null,
	
    // stores a reference to the last selected category link
    lastCategoryLink: null,
	
	ajax_page: 'ajax_pages/quick_links.php',
	
	init: function() {
		
		
		$p.addEvent('#site-links','click', function(e) {
			system.selectSiteLink(e, $p.$('#LinkURL') );
		});
		
		// create a UI Menu using the UI script framework
        var items_array = new Array();
        $p.all(".category-list li a", function(el, i) {
            var mi = {
                id: el.id,
                name: el.innerHTML,
                title: el.title,

                // menus will call this action and supply the menu item as a parameter, so define the
                // action to use the supplied object
                action: function(mi) {
                    quick_links.moveLinksToCategory( mi );
                }
            };

            items_array[i] = mi;
        });

        ui.menu( $p.$("#move-link"), {
            items: items_array
        });

        $p.addEvent('delete-link', 'click', function() {
            quick_links.deleteLinks();
        });
		
        $p.addEvent('add-cat-link', 'click', function() {
            quick_links.showCategoryAddWindow();
        });
		
		$p.addEvent('del-cat-link', 'click', function() {
            quick_links.deleteLinkCategory();
        });
		
        $p.addEvent('add-cat-btn', 'click', function() {
            quick_links.addNewCategory();
        });
		
		$p.addEvent('cancel-btn','click',function() {
			quick_links.hideCategoryAddWindow();
		});
		
        $p.all(".category-list li a", function(el) {
            el.onclick = function() {
                // load the quick_links in this category and indicate it as selected
                quick_links.loadLinks(this);
				
                return false;
            };
					
        });
		
        // load the quick_links in the first category, if we are not the list page
        var firstCat = $p.$(".category-list li:first-child a");
        if( firstCat != null ) {
            quick_links.loadLinks( firstCat );
        } else if( document.getElementById('news-content') ) {
            document.getElementById('news-content').innerHTML = '<span>No Link Categories Exist For This Site. Please Create Link Categories To Group Links</span>';
        }
	},
	
	/**
	 * Loads the list of links in the specified category
	 *
	 * @param catLink the link element representing the category
	 * @param page an integer representing the page for which to load data for
	 */
    loadLinks: function(catLink, page) {
        // if a category link is not specified, check if a previous one exists and use that instead
        if( catLink == null && quick_links.lastCategoryLink != null ) {
            catLink = quick_links.lastCategoryLink;
		
        // if one does not exist, then inform and exit
        } else if( catLink == null && quick_links.lastCategoryLink == null) {
            alert('Cannot Load Links If Category Link Is Not Specified');
            return;
        }
		
        //clear any previously selected list items
        $p.all(".category-list li", function(li) {
            li.className = '';
        });
		
        // set a variable to determine the limit for the number of pages to load
        var limit = 25;
		
        var catName = catLink.innerHTML;
        var catId = catLink.id;
        catLink.parentNode.className = 'selected';
		
        // cache the currently selected category id
        quick_links.category_id = catId;
		
        // cache the last category link
        quick_links.lastCategoryLink = catLink;
		
        // update the article list header
        $p(".articles-pane .pane-header").html('Quick Links In ' + catName);
		
        // build the query to load the news based on the category id
        var query = "action=load_links&category=" + catId + "&limit=" + limit;
		
        // if a specific page is specified, then ammend the query to include that
        // also add the option to not reload the articles-total data so that the navigation
        // bar would not be regenerated
        if( page ) {
            query += "&start=" + page + "&no-total=true";
        }

        $p.setLoaderMessage("Loading Links In " + catName + ". Please Wait...");
        $p.post(quick_links.ajax_page, query, function(data) {
			
			$p("#news-content").html(data);
			
            // obtain the information about the total number of articles in this category
            // and generate a dynamic list of page links
            if( document.getElementById("links-total") ) {
                var total = document.getElementById("links-total").value;
                var total_pages = Math.ceil((total / limit));
				
                // get the footer pane and clear the contents
                var paneFooter = $p.$(".articles-pane .pane-footer");
                paneFooter.innerHTML = "<b>Pages: </b> ";
				
                for(var i = 0; i < total_pages; i++) {
                    var a = document.createElement("a");
                    a.setAttribute("href","#");
                    a.id = "page-" + i;
                    a.className = "nav-link";
					
                    // if this is the first link, then indicate that this is the selected page
                    if(i == 0 ) {
                        a.className = "selected";
                    }
					
                    a.innerHTML = (i + 1);
					
                    // add the necessary callback to the link to enable page loading
                    a.onclick = function() {
                        $p.all(".pane-footer a", function(el) {
                            el.className = "nav-link";
                        });
						
                        this.className = "selected";
						
                        var p = this.id.split("-")[1];
                        quick_links.loadLinks( quick_links.lastCategoryLink, p);
                    };
					
                    paneFooter.appendChild( a );
                }
            }

            // register the checkAll checkbox to be able to select all displayed messages
            $p.addEvent('checkAll', 'click', function() {
				
                // select all input fields in table-cells in the data-table component
                $p.all(".cms-data-table td input[type=checkbox]", function(el) {
                    el.checked = $p.$('checkAll').checked;
                });
            });
			
            // register all edit-links
            $p.all(".cms-data-table .edit-link", function(el) {
                el.onclick = function(e) {
                    //quick_links.editLink( this.id );
                    location.href = '?edit&id=' + this.id;
                    return false;
                };
            });
						
            // register all edit-links
            $p.all(".cms-data-table .delete-link", function(el) {
                el.onclick = function(e) {
                    quick_links.deleteLink( this.id );
                    return false;
                };
            });
			
            // register all the publish or unpublish-links
            $p.all(".cms-data-table .cms-publish-link, .cms-data-table .cms-unpublish-link", function(el) {
                el.onclick = function() {
                    if( el.className == 'cms-publish-link' ) {
                        quick_links.publishLink('unpublish', this );
                    } else {
                        quick_links.publishLink('publish', this );
                    }
					
                    return false;
                };
            });
        });
    },
	
	addNewCategory: function() {
        var query = "action=add_category&" + $p("#catForm").serialize();

        $p.all("#catForm input",function(el) {
            el.disabled = true;
        });
		
        // post the data to the server
        $p.post(quick_links.ajax_page, query, function(data) {
			
            if( JSON ) {
                var obj = JSON.parse(data);
                var a = document.createElement("a");
                a.id = obj.id;
                a.setAttribute("href","#");
                a.innerHTML = obj.categoryName;
                a.title = obj.categoryDesc;
                a.onclick = function() {
                    quick_links.loadLinks(this);
                    return false;
                };
					
                var li = document.createElement("li");
                li.appendChild(a);
					
                $p.$(".category-list").appendChild(li);
				
                $p.hide("catAddDiv");
            }
			
            // re-enable the input fields
            $p.all("#catForm input",function(el) {
                el.disabled = false;
            });
        });
    },
	
    deleteLink: function(article_id) {
        $p.showConfirmMessage({
            title: 'Confirm Link Delete',
            content: "Do you want to delete the specified articles from this site?",
            okButtonText: 'Continue Delete',
            okButtonAction: function() {
                var query = "action=delete_links&link_ids=" + article_id;
                $p.post(quick_links.ajax_page, query, function() {
                    $p("#article-row-" + article_id ).remove();
                });
            }
        });
    },
	
    /**
     * Deletes the currently selected (checked) articles in the article display list
     *
     */
    deleteLinks: function() {
        /**
         * it would have been so much easier to use the following selector
         * .cms-data-table td input[type=checkbox]:checked
         * but IE8 does not support the :checked pseudo class, so we will need to
         * do the checking manually in order to be cross platform compartible
         */
        var checked = quick_links.getCheckedLinks();
		
        if( checked.length == 0 ) {
            $p.showMessage({
				title:"Data Error",
				content: "No Links Selected. Please Select Links To Delete"
			});
			
            return;
        }
		
        var ids = "";
        for(var i = 0; i < checked.length; i++) {
            ids += checked[i].value;
			
            if( i < checked.length - 1) {
                ids += ",";
            }
        }
		
        $p.showConfirmMessage({
            title: 'Confirm Link Delete',
            content: "Do you want to delete the specified links from this site?",
            okButtonText: 'Continue Delete',
            okButtonAction: function() {
				
                var query = "action=delete_links&link_ids=" + ids;
                $p.post(quick_links.ajax_page, query, function(data) {
                    quick_links.removeSelectedLinks();
                });
            }
        });
    },
	
    deleteLinkCategory: function() {
        var lastCat = quick_links.lastCategoryLink;
		
        $p.showConfirmMessage({
            title: "Confirm Links Category Delete",
            content: "This will delete all news articles in the <b>" + lastCat.innerHTML + "</b> category. "
            + "Do you want to continue the delete of this category?",
			width: '400px',
            okButtonText: "Delete Category",
            okButtonAction: function() {
                var query = "action=delete_category&category_id=" + quick_links.lastCategoryLink.id ;
                $p.post(quick_links.ajax_page, query, function() {
                    quick_links.lastCategoryLink.parentNode.removeChild( quick_links.lastCategoryLink );
                });
            }
        });
    },
	
	publishLink: function(action, linkEl) {
        var query = "action=" + action + "&id="	+ linkEl.id;
		
        $p.post( quick_links.ajax_page, query, function() {
            if( action == "publish" ) {
                linkEl.className = 'cms-publish-link';
                linkEl.title = 'Published (Click To Unpublish)';
                linkEl.onclick = function() {
                    quick_links.publishLink('unpublish', this);
                }
            } else {
                linkEl.className = 'cms-unpublish-link';
                linkEl.title = 'Unpublished (Click To Publish Now)';
                linkEl.onclick = function() {
                    quick_links.publishLink('publish', this);
                }
            }
        });
    },
	
	moveLinksToCategory: function(menuLink) {
        var selected = quick_links.getCheckedLinks();

        if( selected.length == 0 ) {
            alert("Please Select Links To Be Moved");
            return;
        }

        var msg_ids = "";
        for(var i = 0; i < selected.length; i++) {
            msg_ids += selected[i].value;

            if( i < selected.length - 1 ) {
                msg_ids += ",";
            }
        }

        var query = "action=move_links&category_id=" + menuLink.id + "&msg_ids=" + msg_ids;
        
        //$p.setLoaderMessage("Moving Selected Messages To <b>" + menuLink.innerHTML + "</b>");
        $p.post( quick_links.ajax_page, query,  function(data) {
            quick_links.removeSelectedLinks();
        });
    },

    removeSelectedLinks: function() {
        // select all checkbox fields in table-cells in the data-table component
        $p.all(".cms-data-table td input[type=checkbox]", function(el) {
            if( el.checked ) {
                $p("#article-row-" + el.value ).remove();
            }
        });

        // if only header row remains, then add an instruction row
        if( $p.all(".cms-data-table tbody tr").length == 1 ) {

            var td = document.createElement("td");
                td.colSpan = 3;
                td.appendChild( document.createTextNode("No Links Available In This Category") );

            var tr = document.createElement("tr");
                tr.appendChild(td);

            var table = $p.$(".cms-data-table tbody");
                table.appendChild(tr);

        }
    },

    getCheckedLinks: function() {
        var checks = $p.all(".cms-data-table td input[type=checkbox]");

        var checked = [];
        for(var i = 0, j = 0; i < checks.length; i++ ){
            if( checks[i].checked ) {
                checked[j++] = checks[i];
            }
        }

        return checked;
    },
	
    showCategoryAddWindow: function() {
        //document.getElementById("catAddDiv").style.visibility = "visible";
        $p.show("catAddDiv");
    },
	
    hideCategoryAddWindow: function() {
        //document.getElementById("catAddDiv").style.visibility = "hidden";
        $p.hide("catAddDiv");
    }	
};